using System;
using System.Collections.Generic;

public class BidirectionDictionary<K, V> where K : class where V : class
{
    private Dictionary<K, V> keyValueDict = new Dictionary<K, V>();
    private Dictionary<V, K> valueKeyDict = new Dictionary<V, K>();
    public bool ContainsKey(K key)
    {
        return keyValueDict.ContainsKey(key);
    }
    public bool ContainsValue(V value)
    {
        return valueKeyDict.ContainsKey(value);
    }
    public V GetValueByKey(K key)
    {
        if (ContainsKey(key))
        {
            return keyValueDict[key];
        }
        else
        {
            throw new Exception();
        }
    }
    public K GetKeyByValue(V value)
    {
        if (ContainsValue(value))
        {
            return valueKeyDict[value];
        }
        else
        {
            throw new Exception();
        }
    }
    public void Add(K key, V value)
    {
        if (key == null || value == null || keyValueDict.ContainsKey(key) || valueKeyDict.ContainsKey(value))
        {
            throw new Exception();
        }
        keyValueDict.Add(key, value);
        valueKeyDict.Add(value, key);
    }
    public void RemoveByKey(K key)
    {
        V value;
        if (!keyValueDict.ContainsKey(key) || (value = keyValueDict[key]) == null || !valueKeyDict.ContainsKey(value))
        {
            throw new Exception();
        }
        keyValueDict.Remove(key);
        valueKeyDict.Remove(value);
    }
    public void RemoveByValue(V value)
    {
        K key;
        if (!valueKeyDict.ContainsKey(value) || (key = valueKeyDict[value]) == null || !keyValueDict.ContainsKey(key))
        {
            throw new Exception();
        }
        valueKeyDict.Remove(value);
        keyValueDict.Remove(key);
    }
    public void Clear()
    {
        keyValueDict.Clear();
        valueKeyDict.Clear();
    }
    public int GetCount()
    {
        if (keyValueDict.Count != valueKeyDict.Count)
        {
            throw new Exception();
        }
        return keyValueDict.Count;
    }
}
